package com.attendance.config;

import com.alibaba.fastjson2.JSON;
import com.attendance.entity.User;
import com.attendance.service.UserService;
import com.attendance.service.impl.UserServiceImpl;
import com.attendance.utils.ResponseInfo;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;

@Component
public class OVAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private UserServiceImpl service;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) throws IOException, ServletException {
        AuthenticationSuccessHandler.super.onAuthenticationSuccess(request, response, chain, authentication);
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        Object principal = authentication.getPrincipal(); // 获取用户身份信息
        Object credentials = authentication.getCredentials(); // 获取用户凭证信息
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities(); // 获取用户权限信息
        HashMap<Object, Object> result = new HashMap<>();
        User user = service.searchInfoByEmail(authentication.getName());
        result.put("principal", principal);
        result.put("credentials", credentials);
        result.put("authorities", authorities);
        result.put("userInfo", user);


        // 数据格式化 json
        String json = JSON.toJSONString(ResponseInfo.success(result, "登录成功"));
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);

    }

}
